package client.dialog;

import javafx.geometry.Insets;
import javafx.scene.control.*;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;

import java.util.List;
import java.util.Optional;
import java.util.function.BiConsumer;

public class MuteMemberDialog {

    public static void show(List<String> memberNames, List<String> mutedNames, BiConsumer<String, Boolean> onMuteToggle) {
        Dialog<Void> dialog = new Dialog<>();
        dialog.setTitle("群成员禁言管理");
        dialog.setHeaderText("点击按钮切换禁言状态");

        dialog.getDialogPane().getStylesheets().add(
                MuteMemberDialog.class.getResource("/css/dialog.css").toExternalForm()
        );
        dialog.getDialogPane().getStyleClass().addAll("custom-dialog", "red");


        ButtonType closeButton = new ButtonType("关闭", ButtonBar.ButtonData.CANCEL_CLOSE);
        dialog.getDialogPane().getButtonTypes().addAll(closeButton);

        VBox vbox = new VBox(10);
        vbox.setPadding(new Insets(10));
        dialog.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);

        for (String name : memberNames) {
            final boolean[] isMuted = { mutedNames.contains(name) };

            Label nameLabel = new Label(name);
            nameLabel.setStyle("-fx-font-size: 14px;");

            Button muteBtn = new Button(isMuted[0] ? "已禁言" : "禁言");
            updateButtonStyle(muteBtn, isMuted[0]);

            muteBtn.setOnAction(e -> {
                boolean targetMute = !isMuted[0];
                String actionText = targetMute ? "禁言" : "取消禁言";

                Alert confirm = new Alert(Alert.AlertType.CONFIRMATION,
                        "确定要" + actionText + "该成员吗？",
                        ButtonType.YES, ButtonType.NO);
                confirm.setHeaderText(null);
                Optional<ButtonType> result = confirm.showAndWait();

                if (result.isPresent() && result.get() == ButtonType.YES) {
                    if (onMuteToggle != null) {
                        onMuteToggle.accept(name, targetMute);
                    }
                    isMuted[0] = targetMute;
                    muteBtn.setText(isMuted[0] ? "已禁言" : "禁言");
                    updateButtonStyle(muteBtn, isMuted[0]);
                }
            });

            ToolBar row = new ToolBar(nameLabel, muteBtn);
            row.setStyle("-fx-background-color: transparent; -fx-padding: 0;");
            vbox.getChildren().add(row);
        }

        dialog.getDialogPane().setContent(new ScrollPane(vbox));
        dialog.showAndWait();
    }

    private static void updateButtonStyle(Button button, boolean muted) {
        button.getStyleClass().removeAll("button-muted", "button-unmuted");
        if (muted) {
            button.getStyleClass().add("button-muted");
        } else {
            button.getStyleClass().add("button-unmuted");
        }
    }
}
